import {createRouter, createWebHashHistory} from 'vue-router'
import { routes } from './router.config'
import { nextTick } from 'vue'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/store/modules/user';
import { clearAllCoolies, getTokenFromCookie } from '@/utils/cookie-util';
import { localClear } from '@/utils/local-util';
NProgress.configure({easing: 'ease',speed: 500,showSpinner: false,trickleSpeed: 200,minimum: 0.3})
export const router = createRouter({
  history: createWebHashHistory('/web'),
  routes,
  strict: true,
  scrollBehavior: () => ({ left: 0, top: 0 })
});
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  if (to.path === '/404' || to.path === '/login') {
    next();
    return;
  }
  // 验证登录
  const token = getTokenFromCookie();
  if (!token) {
    clearAllCoolies();
    localClear();
    next({ path: '/login' });
    return;
  }
  if (to.path == '/home') {
    next();
    useUserStore().setTagNav(to, from);
    return;
  }
  useUserStore().setTagNav(to, from);
  if (to.meta.keepAlive) {
    nextTick(() => {
      useUserStore().pushKeepAliveIncludes(to.name?.toString());
    });
  }
  next()
});

router.afterEach(() => {
  NProgress.done();
});